﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SharingCenter.Web.Classes;
using SharingCenter.Web.Classes.enums;

namespace SharingCenter.Web.User.Message
{
    using SharingCenter.Web.Classes.Messages;
    using System.Reflection;
    using System.Xml.Linq;
    public partial class Messages : MessagePageBase
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            LinqDataSource1.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource1_Selecting);
            ListView1.ItemDataBound += new EventHandler<ListViewItemEventArgs>(ListView1_ItemDataBound);            
        }

        void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                Sc_SiteMessage msg = (Sc_SiteMessage)((ListViewDataItem)e.Item).DataItem;
                Panel p = (Panel)e.Item.FindControl("cntPanel");
                Literal l = new Literal();
                l.Text = TransformContext(ref msg);
                p.Controls.Add(l);
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Profile.Website.LastMessageRetrievalDate < DateTime.Now)
            {
                Profile.Website.LastMessageRetrievalDate = DateTime.Now;
                MessageOperations.MarkMessageRead(Profile.UserId, Profile.Website.LastMessageRetrievalDate);
            }
        }

        string TransformContext(ref Sc_SiteMessage msg)
        {
            ClassLibrary.StringHelper h = new ClassLibrary.StringHelper(msg.ContextXml.ToString());
            XAttribute folderAttr = msg.ContextXml.Attribute("XsltFolderInMod");
            XElement trans = XElement.Parse(ContextConversion.GetTransformedXml(h.AsMemoryStream, folderAttr.Value, "MessageContextTransform.xslt", msg.EventName, msg.SenderUserId, msg.MessageDate.ToString()));
            XElement contentToRender = trans.Element("Content");
            ContextConversion.TransformControls(ref contentToRender, Page);
           
            return ClassLibrary.LinqToXmlHelper.GetInnerXml(contentToRender);
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            Profile.Website.LastMessageRetrievalDate = DateTime.Now;
            using (scDataContext cxt = new scDataContext())
            {
                e.Result = cxt.GetMessagesByUserId(Profile.UserId).ToList();
            }
            Profile.Save();
            //e.Result = scDataContext.Instance.GetMessagesByUserId(Profile.UserId).ToList();
        }
    }
}
